import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class FormFieldItem extends ConsumerStatefulWidget {
  final String label;
  final String? value;
  final String? hintText;
  final bool isRequired;
  final bool isEditable;
  final bool showArrow;
  final VoidCallback? onTap;
  final ValueChanged<String>? onChanged;
  final TextInputType? keyboardType;
  final int maxLines;
  final Axis layoutDirection;
  final Color? backgroundColor;
  final Widget? trailing;
  final ProviderListenable<String?>? watchProvider;

  const FormFieldItem({
    super.key,
    required this.label,
    this.value,
    this.hintText,
    this.isRequired = true,
    this.isEditable = true,
    this.showArrow = false,
    this.onTap,
    this.onChanged,
    this.keyboardType,
    this.maxLines = 1,
    this.layoutDirection = Axis.horizontal,
    this.backgroundColor,
    this.trailing,
    this.watchProvider,
  });

  @override
  ConsumerState<FormFieldItem> createState() => _FormFieldItemState();
}

class _FormFieldItemState extends ConsumerState<FormFieldItem> {
  late final TextEditingController _controller;
  late final FocusNode _focusNode;
  ProviderSubscription<String?>? _providerSub;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.value ?? '');
    _focusNode = FocusNode();

    // 监听外部 Provider
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;

      if (widget.watchProvider != null) {
        _providerSub?.close();
        _providerSub = ref.listenManual<String?>(widget.watchProvider!, (
          prev,
          next,
        ) {
          // 仅在未获取焦点时同步外部值
          if (!_focusNode.hasFocus && next != null && widget.isEditable) {
            _controller.text = next;
          }
        });
      }
    });

    // 焦点失去时同步外部值，防止 Tab 切换后显示空
    _focusNode.addListener(() {
      if (!_focusNode.hasFocus) {
        final externalValue = widget.watchProvider != null
            ? ref.read(widget.watchProvider!)
            : widget.value;
        if (externalValue != null && externalValue != _controller.text) {
          _controller.text = externalValue;
        }
      }
    });
  }

  @override
  void didUpdateWidget(covariant FormFieldItem oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当外部 value 更新时，如果没聚焦，更新 controller
    final externalValue = widget.watchProvider != null
        ? ref.read(widget.watchProvider!)
        : widget.value;
    if (!_focusNode.hasFocus &&
        externalValue != null &&
        externalValue != _controller.text) {
      _controller.text = externalValue;
    }
  }

  @override
  void dispose() {
    _providerSub?.close();
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget.backgroundColor ?? Colors.white,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16),
            child: widget.layoutDirection == Axis.horizontal
                ? _buildHorizontal(context)
                : _buildVertical(context),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Container(height: 1, color: Colors.grey.shade200),
          ),
        ],
      ),
    );
  }

  Widget _buildHorizontal(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 16),
          child: SizedBox(
            width: 150,
            child: Row(
              children: [
                Text(
                  widget.label,
                  style: const TextStyle(fontSize: 16, color: Colors.black87),
                ),
                if (widget.isRequired) ...[
                  const SizedBox(width: 4),
                  const Text(
                    '*',
                    style: TextStyle(fontSize: 16, color: Colors.red),
                  ),
                ],
              ],
            ),
          ),
        ),
        const SizedBox(width: 16),
        Expanded(child: widget.trailing ?? _buildContent()),
        if (widget.showArrow) ...[
          const Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey),
          const SizedBox(width: 16),
        ],
      ],
    );
  }

  Widget _buildVertical(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 16, bottom: 8),
          child: Row(
            children: [
              Text(
                widget.label,
                style: const TextStyle(fontSize: 16, color: Colors.black87),
              ),
              if (widget.isRequired) ...[
                const SizedBox(width: 4),
                const Text(
                  '*',
                  style: TextStyle(fontSize: 16, color: Colors.red),
                ),
              ],
            ],
          ),
        ),
        widget.trailing ?? _buildContent(),
      ],
    );
  }

  Widget _buildContent() {
    if (widget.isEditable) {
      return Padding(
        padding: widget.layoutDirection == Axis.vertical
            ? const EdgeInsets.symmetric(horizontal: 16)
            : const EdgeInsets.only(right: 16),
        child: TextField(
          controller: _controller,
          focusNode: _focusNode,
          keyboardType: widget.keyboardType,
          maxLines: widget.maxLines,
          textAlign: widget.layoutDirection == Axis.horizontal
              ? TextAlign.right
              : TextAlign.left,
          decoration: InputDecoration(
            hintText: widget.hintText,
            hintStyle: const TextStyle(color: Colors.grey),
            border: InputBorder.none,
            isDense: true,
            alignLabelWithHint: true,
          ),
          style: const TextStyle(fontSize: 16, color: Colors.black87),
          onChanged: widget.onChanged,
          onTap: widget.onTap,
          textInputAction: widget.maxLines > 1 ? TextInputAction.done : null,
          onSubmitted: (_) => FocusScope.of(context).unfocus(),
        ),
      );
    } else {
      final value = widget.watchProvider != null
          ? ref.watch(widget.watchProvider!)
          : widget.value;

      return GestureDetector(
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
          widget.onTap?.call();
        },
        behavior: HitTestBehavior.opaque,
        child: Container(
          constraints: const BoxConstraints(minHeight: 24),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          alignment: widget.layoutDirection == Axis.horizontal
              ? Alignment.centerRight
              : Alignment.centerLeft,
          child: Text(
            (value?.isNotEmpty == true) ? value! : widget.hintText ?? '',
            style: TextStyle(
              fontSize: 16,
              color: (value?.isNotEmpty == true) ? Colors.black87 : Colors.grey,
            ),
          ),
        ),
      );
    }
  }
}
